﻿using System;
using System.Linq;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using Syncfusion.Drawing;
using Syncfusion.Grouping;
using Syncfusion.Windows.Forms;
using Syncfusion.Windows.Forms.Grid;
using Syncfusion.Windows.Forms.Grid.Grouping;
using Syncfusion.XlsIO;

using PMngr.Data;

namespace PMngr.Main
{
    public partial class WholeTemplate : BaseControl
    {
        private IRepositoryFactory repositoryFactory;
        private string templateFile;

        public WholeTemplate()
        {
            InitializeComponent();

            InitializeGridGrouping();
        }

        public WholeTemplate(IRepositoryFactory repositoryFactory)
            : this()
        {
            this.repositoryFactory = repositoryFactory;
        }

        private void InitializeGridGrouping()
        {
            foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(ProfileModel)))
            {
                var gcd = new GridColumnDescriptor(pd.Name, pd.Name, ProfileModel.Dict[pd.Name], true);
                
                this.gridList.TableDescriptor.Columns.Add(gcd);
            }
            this.gridList.TableDescriptor.Name = @"整体划转";
            this.gridList.TableDescriptor.FrozenColumn = ProfileModel.GetPropertyName(u => u.Name);
            // hide the trivial items
            this.gridList.TableDescriptor.VisibleColumns.Remove(ProfileModel.GetPropertyName(p => p.UserId));
            this.gridList.TableDescriptor.VisibleColumns.Remove(ProfileModel.GetPropertyName(p => p.Checked));
            this.gridList.TableDescriptor.VisibleColumns.Remove(ProfileModel.GetPropertyName(p => p.PrintDate));
            this.gridList.TableDescriptor.VisibleColumns.Remove(ProfileModel.GetPropertyName(p => p.WholeTransferId));
            //
            this.gridList.DataSource = null;
        }

        private void btnProduct_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Files(*.xls)|*.xls";
            saveFileDialog.AddExtension = true;
            saveFileDialog.DefaultExt = ".xls";

            if (saveFileDialog.ShowDialog() == DialogResult.OK && saveFileDialog.CheckPathExists)
            {
                templateFile = saveFileDialog.FileName;

                GenerateTemplate(templateFile);

                LogTrace(String.Format(Utilities.TemplateCompleted, templateFile));

                if (MessageFactory.MessageBoxShow(Utilities.OpenExcelConfirmed) == DialogResult.Yes)
                {
                    var proc = new System.Diagnostics.Process();
                    proc.StartInfo.FileName = saveFileDialog.FileName;
                    proc.Start();
                }
            }
        }      

        private void GenerateTemplate(string file)
        {
            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;
            //
            var template = Application.StartupPath + @".\docs\template.xls";
            IWorkbook workbook = application.Workbooks.Open(template);
            IWorksheet sheet = workbook.Worksheets[0];
            
            #region Validation
            // 性别
            IDataValidation genderValidator = sheet.Range[2, 4, 5000, 4].DataValidation;
            genderValidator.ListOfValues = new[] { "男", "女" };
            genderValidator.PromptBoxText = "选择性别";
            genderValidator.IsPromptBoxVisible = true;
            genderValidator.ShowPromptBox = true;
            // 学历
            IDataValidation xlValidator = sheet.Range[2, 6, 5000, 6].DataValidation;
            xlValidator.ListOfValues = GetItems("SchoolRecord");
            xlValidator.PromptBoxText = "选择学历";
            xlValidator.IsPromptBoxVisible = true;
            xlValidator.ShowPromptBox = true;
            // 学位
            IDataValidation xwValidator = sheet.Range[2, 7, 5000, 7].DataValidation;
            xwValidator.ListOfValues = GetItems("SchoolLevel");
            xwValidator.PromptBoxText = "选择学位";
            xwValidator.IsPromptBoxVisible = true;
            xwValidator.ShowPromptBox = true;
            // 政治面貌 
            IDataValidation mmValidator = sheet.Range[2, 8, 5000, 8].DataValidation;
            mmValidator.ListOfValues = GetItems("PolicyFace");
            mmValidator.PromptBoxText = "选择政治面貌";
            mmValidator.IsPromptBoxVisible = true;
            mmValidator.ShowPromptBox = true;
            // 本人身份
            IDataValidation sfValidator = sheet.Range[2, 12, 5000, 12].DataValidation;
            sfValidator.ListOfValues = GetItems("Identity");
            sfValidator.PromptBoxText = "选择本人身份";
            sfValidator.IsPromptBoxVisible = true;
            sfValidator.ShowPromptBox = true;
            // 技术等级
            IDataValidation djValidator = sheet.Range[2, 15, 5000, 15].DataValidation;
            djValidator.ListOfValues = GetItems("TechGrade");
            djValidator.PromptBoxText = "选择技术等级";
            djValidator.IsPromptBoxVisible = true;
            djValidator.ShowPromptBox = true;           
            // 出生日期
            IDataValidation birthValidator = sheet.Range[2, 3, 5000, 3].DataValidation;
            birthValidator.AllowType = ExcelDataType.Date;
            birthValidator.CompareOperator = ExcelDataValidationComparisonOperator.Between;
            birthValidator.FirstDateTime = new DateTime(1900, 1, 1);
            birthValidator.SecondDateTime = new DateTime(2020, 1, 1);
            birthValidator.ShowErrorBox = true;
            birthValidator.ErrorBoxText = "输入1900/1/1到2020/1/1之间日期";
            birthValidator.ErrorBoxTitle = "错误提示";
            birthValidator.PromptBoxText = "选择正确日期";
            birthValidator.ShowPromptBox = true;
            // 参加工作时间
            IDataValidation workValidator = sheet.Range[2, 17, 5000, 17].DataValidation;
            workValidator.AllowType = ExcelDataType.Date;
            workValidator.CompareOperator = ExcelDataValidationComparisonOperator.Between;
            workValidator.FirstDateTime = new DateTime(1900, 1, 1);
            workValidator.SecondDateTime = new DateTime(2020, 1, 1);
            workValidator.ShowErrorBox = true;
            workValidator.ErrorBoxText = "输入1900/1/1到2020/1/1之间日期";
            workValidator.ErrorBoxTitle = "错误提示";
            workValidator.PromptBoxText = "选择正确日期";
            workValidator.ShowPromptBox = true;
            #endregion         

            //Freeze header row.
            sheet.Range["A2"].FreezePanes();
            //Saving the workbook to disk.
            workbook.SaveAs(file);
            //Close the workbook.
            workbook.Close();
            //No exception will be thrown if there are unsaved workbooks.
            excelEngine.ThrowNotSavedOnDestroy = false;
            excelEngine.Dispose(); 
        }

        public override void InitializeControls()
        {
            gridList.InitializeGridGrouping();

            using (var repository = repositoryFactory.CreateRepository())
            {
                var query = repository.All<Profile>().Take(10).Select(p => new ProfileModel
                                                                               {
                                                                                   UserId = p.UserId,
                                                                                   Name = p.Name,
                                                                                   Nationality = p.Nationality,
                                                                                   BirthDate = p.BirthDate,
                                                                                   Gender = p.Gender,
                                                                                   SchoolRecord = p.SchoolRecord.Name,
                                                                                   SchoolLevel = p.SchoolLevel.Name,
                                                                                   PolicyFace = p.PolicyFace.Name,
                                                                                   MarriedDate = p.MarriedDate,
                                                                                   College = p.College,
                                                                                   Major = p.Major,
                                                                                   InUnit = p.OriginalIn,
                                                                                   OutUnit = p.OriginalOut,
                                                                                   ProfPos = p.ProfPos,
                                                                                   ProfTitle = p.ProfTitle,
                                                                                   PersonalIdentity =
                                                                                       p.PersonalIdentity.Name,
                                                                                   TechGrade = p.TechGrade.Name,
                                                                                   WorkKind = p.WorkKind,
                                                                                   WorkStart = p.WorkStart,
                                                                                   SalaryGrade = p.SalaryGrade,
                                                                                   TransferReason =
                                                                                       p.TransferReason.Name,
                                                                                   RecordDate = p.RecordDate,
                                                                                   ApprovalDate = p.ApprovalDate
                                                                               }).ToList();

                PassThroughGroupingResult queryResults = new PassThroughGroupingResult("Profile", query,
                                                                                       typeof (ProfileModel), 10);
                this.gridList.DataSource = queryResults;
            }
        }

        private string[] GetItems(string type)
        {
            using (var repository = repositoryFactory.CreateRepository())
            {
                var items =
                    repository.Find<ItemBase>(i => i.Type == type && i.IsValid == true).OrderBy(i => i.Order).Select(
                        i => i.Name);
                return items.ToArray();
            }
        }
    }
}
